/*
 * Copyright (C) 2003, Velocityme Partnership
 * SequenceGeneratorBean.java
 *
 * Created on 12 April 2003, 07:18
 */

package com.velocityme.session;

import javax.ejb.*;
import java.util.*;
import com.velocityme.interfaces.*;
import com.velocityme.utility.DataSourceConnection;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;

/**
 *
 * @author  Robert
 * @ejb.bean
 *           type="Stateless"
 *           cmp-version="2.x"
 *           name="SequenceGenerator"
 *           jndi-name="ejb/SequenceGenerator"
 *           view-type="remote"
 *           transaction-type="Container"
 * @ejb.transaction type="Required"
 *
 * @ejb.util generate="physical"
 */
public class SequenceGeneratorBean implements SessionBean {

    private SessionContext m_context;

    /**
     * @ejb:interface-method view-type="remote"
     * @ejb:transaction type="Mandatory"
     **/
    public int getNextNumber(String p_tableName, String p_columnName) throws ServiceUnavailableException, RemoteException {
        Connection connection = null;
        Statement statement = null;
        try {
            connection = DataSourceConnection.getConnection();
            statement = connection.createStatement();
            String sql = "SELECT MAX( " + p_columnName + " ) FROM " + p_tableName;
            ResultSet result = statement.executeQuery(sql);
            int max = -1;
            if (result.next() ) {
                max = result.getInt(1);
                if (max <= 0) max = 1;
            }
            return max + 1;
        }
        catch(SQLException e) {
            throw new ServiceUnavailableException("Sequence number is broken");
        }
        catch(NamingException e) {
            throw new ServiceUnavailableException("JNDI Lookup broken");
        }
        finally {
            try {
                if (statement != null) statement.close();
            }
            catch(Exception e) {}
            try {
                if (connection != null) connection.close();
            }
            catch(Exception e) {}
        }
    }

    /**
     * Create the Session Bean.
     * @throws CreateException 
     * @ejb:create-method view-type="remote"
     */
    public void ejbCreate() throws CreateException {
    }

    public void ejbActivate() throws java.rmi.RemoteException {
    }
    
    public void ejbPassivate() throws java.rmi.RemoteException {
    }
    
    public void ejbRemove() throws java.rmi.RemoteException {
    }
    
    public void setSessionContext(javax.ejb.SessionContext sessionContext) throws java.rmi.RemoteException {
        m_context = sessionContext;
    }
    
}
